package top.jojoace.RequestParam_DTO_Validate.validators;

import top.jojoace.RequestParam_DTO_Validate.dto.PasswordValidatorDTO;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;


/**
 *
 * <h1>自定义验证注解</h1>
 *
 *
 * public interface ConstraintValidator<A extends Annotation, T>
 *     A：要定义的注解
 *     T：要处理的类
 *
 */

/**
 * 传递一个JSON到PasswordValidatorDTO
 * {
 *     "password1":"123",
 *     "password2":"123"
 * }
 * 并检验两次密码是否一致。
 */
public class PasswordValidator implements ConstraintValidator<PasswordEqual, PasswordValidatorDTO> {

    private int min;
    private int max;

    /**
     * 获得 PasswordEqual 注解的参数，并初始化。
     * @param constraintAnnotation
     */
    @Override
    public void initialize(PasswordEqual constraintAnnotation) {
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
    }

    /**
     * 判断
     * @param passwordValidatorDTO
     * @param constraintValidatorContext
     * @return
     */
    @Override
    public boolean isValid(PasswordValidatorDTO passwordValidatorDTO, ConstraintValidatorContext constraintValidatorContext) {
        String password1 = passwordValidatorDTO.getPassword1();
        String password2 = passwordValidatorDTO.getPassword2();
        boolean match = password2.equals(password1);
        return match;
    }
}
